package com.projectbox.web;

import java.util.List;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;

import com.projectbox.model.Project;
import com.projectbox.model.User;
import com.projectbox.service.ProjectService;
import com.projectbox.service.UserService;

@Controller
@RequestMapping("/contribute")
public class ContributeProjectController {

	private Logger logger = LoggerFactory.getLogger(getClass()); 
	
	private UserService userService;
	private ProjectService projectService;
	
	public void setUserService(UserService userService) {
		this.userService = userService;
	}
	
	public void setProjectService(ProjectService projectService) {
		this.projectService = projectService;
	}
	
	@RequestMapping(method = RequestMethod.GET)
	public String displayContributeProjects(Model model) {
		User user = userService.getCurrentUser();
		List<Project> projectList = this.projectService.findContributedProjects(user);
		
		model.addAttribute("projectList", projectList);
		model.addAttribute("user", user);
		
		return "contribute";
	}
	
	@RequestMapping(value="/withdraw", method = RequestMethod.GET)
	public String withdrawProject(@RequestParam(value="pid", required=true) Long pid) {		
		User user = userService.getCurrentUser();
		Project project = this.projectService.findProject(pid);
		
		if (project == null) {
			return "redirect:/error/400.jsp";
		}
		
		// delete the access to that project
		this.projectService.removeProjectContributor(pid, user.getId());
		
		return "redirect:/contribute";
	}
	
}
